package com.eqxiu.ieditor.weixin.event;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eqxiu.ieditor.weixin.dao.WeixinAppDao;
import com.eqxiu.ieditor.weixin.model.WeixinApp;
import com.eqxiu.ieditor.weixin.model.WeixinAppExample;
import com.eqxiu.ieditor.weixin.util.HttpUtils;
import com.eqxiu.ieditor.weixin.util.NotFoundAppIdException;
import com.eqxiu.iom.msg.api.MsgEventApi;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.RelAccount;
import com.eqxiu.user.utils.UserConstants;

public  abstract class AbstractEventListenner {
    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String WECHAT_FOLLOWED = "wechat_followed";

    @Value("${notify.appid}")
    protected String appId;
    @Autowired
    protected UserApi userApi;
    @Autowired
    protected MsgEventApi msgEventApi;
    
    @Autowired
    private WeixinAppDao appDao;

    @Value("${notify.wechat.name}")
    protected String weChatName ;


    protected String getUnionId(String openId){
        logger.info("Subscribe event handler openID = {}",openId);
        logger.info("fetch access token appid={}",appId);
        String token = getWechatToken(appId);
        if(StringUtils.isEmpty(token)) {
            logger.warn("fetch access token fail and return");
            return null;
        }
        logger.info("fetch access token success accessToken = {} , appid={}",token,appId);

        String unionid = getUnionId(token,openId);
        return unionid;
    }

    /**
     * 获取 UnionId
     * @param accessToken
     * @param openId
     * @return
     */
    protected String getUnionId (String accessToken,String openId) {
        logger.info("fetch unionid access token = {},openid={}",accessToken,openId);
        String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s", accessToken, openId);
        String result = null;
        try {
            result = HttpUtils.get(url);
            JSONObject jsonObject = JSON.parseObject(result);
            String unionid = jsonObject.getString("unionid");
            logger.info("fuetch unionid success unionid= {} ",unionid);
            return unionid;
        } catch (IOException e) {
            logger.error("fuetch unionid fail ");
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 获取关联账户
     * @param unionId
     * @return
     */
    protected RelAccount getRelAccount(String unionId){
        String type = UserConstants.TYPE_WECHAT;
        RelAccount relAccount = userApi.getRelAccount(type, unionId);
        logger.info("find ref account = {}",relAccount);
        return relAccount;
    }

    private String getWechatToken(String appId){
        WeixinAppExample example = new WeixinAppExample();
        example.createCriteria().andAppIdEqualTo(appId);
        List<WeixinApp> apps = appDao.selectByExample(example);
        if (apps == null || apps.size() == 0) {
            throw new NotFoundAppIdException("appid " + appId + " not found");
        }
        WeixinApp app = apps.get(0);

        String token = userApi.getWeChatAccessToken(appId, app.getAppSecret());
        return token;
    }
}
